package com.jeeplus.modules.api;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.activity.service.ActivityService;
import com.jeeplus.modules.api.VO.IndexVO;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.tickettype.entity.TicketType;
import com.jeeplus.modules.tickettype.service.TicketTypeService;
import com.jeeplus.modules.topic.entity.Topic;
import com.jeeplus.modules.topic.entity.TopicTicket;
import com.jeeplus.modules.topic.mapper.TopicTicketMapper;
import com.jeeplus.modules.topic.service.TopicService;
import com.jeeplus.modules.userorder.entity.UserOrder;
import com.jeeplus.modules.userorder.service.UserOrderService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/api/common/")
public class CommonController extends BaseController {

    private final TopicTicketMapper topicTicketMapper;
    private final TicketTypeService ticketTypeMapper;
    private final TopicService topicService;
    private final MemberService memberService;
    private final UserOrderService userOrderService;
    private final ActivityService activityService;

    public CommonController(TopicTicketMapper topicTicketMapper, TicketTypeService ticketTypeMapper, TopicService topicService, MemberService memberService, UserOrderService userOrderService, ActivityService activityService) {
        this.topicTicketMapper = topicTicketMapper;
        this.ticketTypeMapper = ticketTypeMapper;
        this.topicService = topicService;
        this.memberService = memberService;
        this.userOrderService = userOrderService;
        this.activityService = activityService;
    }


    /**
     * 查询门票种类
     *
     * @param topicId 主题id
     * @return 门票种类
     */
    @RequestMapping("topicTypes")
    public AjaxJson topicTypes(String topicId) {
        TopicTicket topicTicket = new TopicTicket();
        topicTicket.setTopic(new Topic(topicId));
        List<TopicTicket> list = topicTicketMapper.findList(topicTicket);
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (TopicTicket ticket : list) {
            Map<String, Object> map = new HashMap<>();
            TicketType ticketType = ticketTypeMapper.get(ticket.getTicketType());
            map.put("label", ticketType.getTitle());
            map.put("value", ticketType.getId());
            mapList.add(map);
        }
        return AjaxJson.success().put("typeList", mapList);
    }

    /**
     * 查询主题列表
     *
     * @return 门票种类
     */
    @RequestMapping("topicList")
    public AjaxJson topicList() {
        List<Topic> list = topicService.findList(new Topic());
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Topic topic : list) {
            Map<String, Object> map = new HashMap<>();
            map.put("label", topic.getTitle());
            map.put("value", topic.getId());
            mapList.add(map);
        }
        return AjaxJson.success().put("topicList", mapList);
    }

    /**
     * 查找首页上部的数据
     *
     * @return 数据
     */
    @RequestMapping("getTopData")
    public AjaxJson getTopData() {
        // 查找用户的总数
        Map<String, Object> map = new HashMap<>();
        List<Member> list = memberService.findList(new Member());
        map.put("userNum", list.size());
        // 查找当日订单量
        UserOrder userOrder = new UserOrder();
        userOrder.setDataScope(" and TO_DAYS(a.create_date) = TO_DAYS(NOW())");
        List<UserOrder> list1 = userOrderService.findList(userOrder);
        map.put("todayOrder", list1.size());
        // 查询今日收益
        String o = userOrderService.executeGetSql("SELECT ifnull(SUM(pay_amount), 0) FROM t_user_order WHERE order_state in ('2', '3', '4') and TO_DAYS(create_date) = TO_DAYS(NOW())").toString();
        map.put("todayIncome", new BigDecimal(o).setScale(2, BigDecimal.ROUND_HALF_UP));
        // 查询今日入场人数
        String people = userOrderService.executeGetSql("SELECT ifnull(SUM(quantity), 0) FROM t_user_order WHERE order_state = '3' and TO_DAYS(create_date) = TO_DAYS(NOW())").toString();
        map.put("todayPeople", people);

        // 查询昨日的订单
        UserOrder userOrder1 = new UserOrder();
        userOrder1.setDataScope(" and TO_DAYS(NOW()) - TO_DAYS(a.create_date) <= 1 AND TO_DAYS(NOW()) - TO_DAYS(a.create_date) > 0");
        List<UserOrder> list2 = userOrderService.findList(userOrder1);
        map.put("yesOrder", list2.size());

        // 查询昨日的收益
        String o1 = userOrderService.executeGetSql("SELECT ifnull(SUM(pay_amount), 0) FROM t_user_order WHERE order_state in ('2', '3', '4') and TO_DAYS(NOW()) - TO_DAYS(create_date) <= 1 AND TO_DAYS(NOW()) - TO_DAYS(create_date) > 0").toString();
        map.put("yesIncome", new BigDecimal(o1).setScale(2, BigDecimal.ROUND_HALF_UP));

        // 查找昨日的入场人数
        String people1 = userOrderService.executeGetSql("SELECT ifnull(SUM(quantity), 0) FROM t_user_order WHERE order_state = '3' and TO_DAYS(NOW()) - TO_DAYS(create_date) <= 1 AND TO_DAYS(NOW()) - TO_DAYS(create_date) > 0").toString();
        map.put("yesPeople", people1);
        return AjaxJson.success().put("data", map);
    }

    /**
     * 根据日期查询数据
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return 数据
     */
    @RequestMapping("dateNum")
    public AjaxJson dateNum(String startDate, String endDate, String topicId) {
        // 查询用户量
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(startDate)) {
            // 用户量
            Member member = new Member();
            member.setDataScope(" and DATE_FORMAT(a.create_date, '%Y-%m-%d') > '" + startDate + "'");
            List<Member> list = memberService.findList(member);
            map.put("user", list.size());
            // 订单量
            UserOrder userOrder = new UserOrder();
            userOrder.setTopic(new Topic(topicId));
            userOrder.setDataScope(" and DATE_FORMAT(a.create_date, '%Y-%m-%d') > '" + startDate + "'");
            List<UserOrder> list1 = userOrderService.findList(userOrder);
            map.put("order", list1.size());
            // 收益量
            String o = userOrderService.executeGetSql("SELECT ifnull(SUM(pay_amount), 0) FROM t_user_order WHERE order_state in ('2', '3', '4') and DATE_FORMAT(create_date, '%Y-%m-%d') > '" + startDate + "'").toString();
            map.put("income", new BigDecimal(o).setScale(2, BigDecimal.ROUND_HALF_UP));
            // 入场人数
            String people = userOrderService.executeGetSql("SELECT ifnull(SUM(quantity), 0) FROM t_user_order WHERE order_state = '3' and DATE_FORMAT(create_date, '%Y-%m-%d') > '" + startDate + "'").toString();
            map.put("people", people);
            if (StringUtils.isNotBlank(topicId)) {
                String o1 = userOrderService.executeGetSql("SELECT ifnull(SUM(pay_amount), 0) FROM t_user_order WHERE order_state in ('2', '3', '4') and topic_id = '" + topicId + "' and DATE_FORMAT(create_date, '%Y-%m-%d') > '" + startDate + "'").toString();
                map.put("income", new BigDecimal(o1).setScale(2, BigDecimal.ROUND_HALF_UP));
                // 入场人数
                String people1 = userOrderService.executeGetSql("SELECT ifnull(SUM(quantity), 0) FROM t_user_order WHERE order_state = '3' and topic_id = '" + topicId + "'  and DATE_FORMAT(create_date, '%Y-%m-%d') > '" + startDate + "'").toString();
                map.put("people", people1);
            }
        }
        if (StringUtils.isNotBlank(endDate)) {
            // 用户量
            Member member = new Member();
            member.setDataScope(" and DATE_FORMAT(a.create_date, '%Y-%m-%d') < '" + endDate + "'");
            List<Member> list = memberService.findList(member);
            map.put("user", list.size());
            // 订单量
            UserOrder userOrder = new UserOrder();
            userOrder.setDataScope(" and DATE_FORMAT(a.create_date, '%Y-%m-%d') < '" + endDate + "'");
            userOrder.setTopic(new Topic(topicId));
            List<UserOrder> list1 = userOrderService.findList(userOrder);
            map.put("order", list1.size());
            // 收益量
            String o = userOrderService.executeGetSql("SELECT ifnull(SUM(pay_amount), 0) FROM t_user_order WHERE order_state in ('2', '3', '4') and DATE_FORMAT(create_date, '%Y-%m-%d') < '" + endDate + "'").toString();
            map.put("income", new BigDecimal(o).setScale(2, BigDecimal.ROUND_HALF_UP));
            // 入场人数
            String people = userOrderService.executeGetSql("SELECT ifnull(SUM(quantity), 0) FROM t_user_order WHERE order_state = '3' and DATE_FORMAT(create_date, '%Y-%m-%d') < '" + endDate + "'").toString();
            map.put("people", people);
            if (StringUtils.isNotBlank(topicId)) {
                // 收益量
                String o1 = userOrderService.executeGetSql("SELECT ifnull(SUM(pay_amount), 0) FROM t_user_order WHERE order_state in ('2', '3', '4') and topic_id = '" + topicId + "'  and DATE_FORMAT(create_date, '%Y-%m-%d') < '" + endDate + "'").toString();
                map.put("income", new BigDecimal(o1).setScale(2, BigDecimal.ROUND_HALF_UP));
                // 入场人数
                String people1 = userOrderService.executeGetSql("SELECT ifnull(SUM(quantity), 0) FROM t_user_order WHERE order_state = '3' and topic_id = '" + topicId + "'  and DATE_FORMAT(create_date, '%Y-%m-%d') < '" + endDate + "'").toString();
                map.put("people", people1);
            }
        }
        if (StringUtils.isNotBlank(endDate) && StringUtils.isNotBlank(startDate)) {
            // 用户量
            Member member = new Member();
            member.setDataScope(" and DATE_FORMAT(a.create_date, '%Y-%m-%d') BETWEEN '" + startDate + "' AND '" + endDate + "'");
            List<Member> list = memberService.findList(member);
            map.put("user", list.size());
            // 订单量
            UserOrder userOrder = new UserOrder();
            userOrder.setTopic(new Topic(topicId));
            userOrder.setDataScope(" and DATE_FORMAT(a.create_date, '%Y-%m-%d') BETWEEN '" + startDate + "' AND '" + endDate + "'");
            List<UserOrder> list1 = userOrderService.findList(userOrder);
            map.put("order", list1.size());
            // 收益量
            String o = userOrderService.executeGetSql("SELECT ifnull(SUM(pay_amount), 0) FROM t_user_order WHERE order_state in ('2', '3', '4') and DATE_FORMAT(create_date, '%Y-%m-%d') BETWEEN '" + startDate + "' AND '" + endDate + "'").toString();
            map.put("income", new BigDecimal(o).setScale(2, BigDecimal.ROUND_HALF_UP));
            // 入场人数
            String people = userOrderService.executeGetSql("SELECT ifnull(SUM(quantity), 0) FROM t_user_order WHERE order_state = '3' and DATE_FORMAT(create_date, '%Y-%m-%d') BETWEEN '" + startDate + "' AND '" + endDate + "'").toString();
            map.put("people", people);
            if (StringUtils.isNotBlank(topicId)) {
                // 收益量
                String o1 = userOrderService.executeGetSql("SELECT ifnull(SUM(pay_amount), 0) FROM t_user_order WHERE order_state in ('2', '3', '4') and topic_id = '" + topicId + "' and DATE_FORMAT(create_date, '%Y-%m-%d') BETWEEN '" + startDate + "' AND '" + endDate + "'").toString();
                map.put("income", new BigDecimal(o1).setScale(2, BigDecimal.ROUND_HALF_UP));
                // 入场人数
                String people1 = userOrderService.executeGetSql("SELECT ifnull(SUM(quantity), 0) FROM t_user_order WHERE order_state = '3' and topic_id = '" + topicId + "'  and DATE_FORMAT(create_date, '%Y-%m-%d') BETWEEN '" + startDate + "' AND '" + endDate + "'").toString();
                map.put("people", people1);
            }
        }
        if (StringUtils.isBlank(startDate) && StringUtils.isBlank(endDate)) {
            // 用户量
            Member member = new Member();
            List<Member> list = memberService.findList(member);
            map.put("user", list.size());
            // 订单量
            UserOrder userOrder = new UserOrder();
            userOrder.setTopic(new Topic(topicId));
            List<UserOrder> list1 = userOrderService.findList(userOrder);
            map.put("order", list1.size());
            // 收益量
            String o = userOrderService.executeGetSql("SELECT ifnull(SUM(pay_amount), 0) FROM t_user_order WHERE order_state in ('2', '3', '4')").toString();
            map.put("income", new BigDecimal(o).setScale(2, BigDecimal.ROUND_HALF_UP));
            // 入场人数
            String people = userOrderService.executeGetSql("SELECT ifnull(SUM(quantity), 0) FROM t_user_order WHERE order_state = '3'").toString();
            map.put("people", people);
            if (StringUtils.isNotBlank(topicId)) {
                // 收益量
                String o1 = userOrderService.executeGetSql("SELECT ifnull(SUM(pay_amount), 0) FROM t_user_order WHERE order_state in ('2', '3', '4') and topic_id = '" + topicId + "'").toString();
                map.put("income", new BigDecimal(o1).setScale(2, BigDecimal.ROUND_HALF_UP));
                // 入场人数
                String people1 = userOrderService.executeGetSql("SELECT ifnull(SUM(quantity), 0) FROM t_user_order WHERE order_state = '3' and topic_id = '" + topicId + "'").toString();
                map.put("people", people1);
            }
        }
        return AjaxJson.success().put("count", map);
    }

    /**
     * 查询日历销量
     *
     * @param yearMonth    日期
     * @param yearMonthDay 日期
     * @param topicId      主题id
     * @return 数据
     */
    @RequestMapping("getDays")
    public AjaxJson getDays(String yearMonth, String yearMonthDay, String topicId) {
        String ymd = ymd(new Date()).substring(0, 7);
        if (StringUtils.isBlank(topicId)) {
            List<Topic> list = topicService.findList(new Topic());
            if (CollectionUtils.isNotEmpty(list)) {
                topicId = list.get(0).getId();
            }
        }
        if (StringUtils.isBlank(yearMonth)) {
            yearMonth = ymd(new Date()).replace("-", "").substring(0, 4);
        }
        int day = getDay(yearMonth);
        List<String> list = new ArrayList<>();
        for (int i = 1; i < day + 1; i++) {
            String s = String.valueOf(i);
            if (s.length() < 2) {
                s = "0" + s;
            }
            list.add(s);
        }
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (String s : list) {
            String d;
            if (StringUtils.isBlank(yearMonthDay)) {
                d = ymd + "-" + s;
            } else {
                d = yearMonthDay + "-" + s;
            }
            // 查询当天的订单数据
            UserOrder userOrder = new UserOrder();
            userOrder.setTopic(new Topic(topicId));
            userOrder.setDataScope(" and DATE_FORMAT(a.create_date, '%Y-%m-%d') = '" + d + "'");
            List<UserOrder> list3 = userOrderService.findList(userOrder);
            // 查询当日是否有活动
            String o = activityService.executeGetSql("SELECT ifnull(SUM(quantity), 0) FROM t_activity where topic_id = '" + topicId + "' and act_date = '" + d + "'").toString();
            Map<String, Object> map = new HashMap<>();
            map.put("day", d);
            map.put("sale", list3.size());
            if (Integer.parseInt(o) > 0) {
                map.put("sur", Integer.parseInt(o) - list3.size());
            } else {
                String o1 = topicTicketMapper.executeGetSql("SELECT ifnull(SUM(stock), 0) FROM t_topic_ticket where topic_id = '" + topicId + "'").toString();
                if (Integer.parseInt(o1) > 0) {
                    map.put("sur", Integer.parseInt(o1) - list3.size());
                }
            }
            mapList.add(map);
        }
        return AjaxJson.success().put("days", mapList);
    }

    // 获取当月的天数
    private static int getDay(String yearMonth) {
        Calendar cal = new GregorianCalendar();
        SimpleDateFormat oSdf = new SimpleDateFormat("", Locale.ENGLISH);
        oSdf.applyPattern("yyyyMM");
        try {
            cal.setTime(oSdf.parse(yearMonth));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    @RequestMapping("week")
    public AjaxJson week() {
        List<IndexVO> week = userOrderService.week();
        return AjaxJson.success().put("week", week);
    }

    @RequestMapping("month")
    public AjaxJson month() {
        List<IndexVO> month = userOrderService.month();
        return AjaxJson.success().put("month", month);
    }

    @RequestMapping("year")
    public AjaxJson year() {
        List<IndexVO> year = userOrderService.year();
        return AjaxJson.success().put("year", year);
    }
}